package com.by.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class StockController {


    @SentinelResource(value = "库存",fallback = "fallback")
    @GetMapping("/stock")
    public String get(int id) {
        int tmp =(int) (Math.random() * 1000);
        System.out.println("耗费时间："+tmp);
       /* try {
            Thread.sleep(tmp);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/
        /*if(tmp%2==0){
            throw new RuntimeException("异常");
        }*/
        return "库存";
    }

    public String fallback(int id, Throwable e) {
        System.out.println("降级处理：" + e.getMessage());
        return "error";
    }

    @PostConstruct
    public void init() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("库存");//设置资源名称
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);//设置熔断策略 慢调用比例
        rule.setCount(0.2);//比例值
        rule.setTimeWindow(5);//设置熔断时长
        rule.setMinRequestAmount(2);//最小请求数
        rule.setStatIntervalMs(2000);//统计时长
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}